<script setup lang="ts">
import {
  getConsultOrderPre,
  createConsultOrder,
  getConsultOrderPayUrl,
} from '@/services/consult';
import type { ConsultOrderPreData } from '@/types/consult';
import { ref, onMounted } from 'vue';
import { useConsultStore } from '@/stores/consult';
import { Dialog, Toast } from 'vant';
import type { Patient } from '@/types/user';
import { getPatient } from '@/services/user';
import { useRouter, onBeforeRouteLeave } from 'vue-router';

// store 实例
const consultStore = useConsultStore();
// 路由管理器实例
const router = useRouter();

// 定义数据
const payInfo = ref<ConsultOrderPreData>();

// 请求订单准备数据（折扣信息）
const loadPayInfo = async () => {
  // 请求参数是否存在
  if (
    consultStore.consult.type === undefined ||
    consultStore.consult.illnessType === undefined
  ) {
    return Toast('缺少就诊类型信息');
  }
  // 发请求获取数据
  const data = await getConsultOrderPre(
    consultStore.consult.type,
    consultStore.consult.illnessType
  );
  payInfo.value = data;
  console.log('订单准备信息', data);
  // 设置生成订单的优惠券id
  consultStore.setCouponId(payInfo.value.couponId);
};
// 请求订单准备数据
onMounted(() => {
  loadPayInfo();
});

// 变量定义
const patient = ref<Patient>();
// 获取患者信息
const loadPatient = async () => {
  if (!consultStore.consult.patientId) return Toast('缺少患者id');
  const data = await getPatient(consultStore.consult.patientId);
  patient.value = data;
  console.log('患者信息', data);
};
onMounted(() => {
  loadPatient();
});

// 支付选项相关
// 支付选项展示/隐藏
const show = ref(false);
// 是否同意支付协议
const agree = ref(false);
// 支付方式 微信-0，支付宝-1
const paymentMethod = ref<0 | 1>();
// 防止多次点击
const loading = ref(false);
// 订单Id
const orderId = ref('');
const submit = async () => {
  if (!agree.value) return Toast('请勾选支付协议');
  try {
    // 订单没有生成返回
    if (loading.value) {
      return;
    }
    // 发起生成订单请求
    loading.value = true;
    const res = await createConsultOrder(consultStore.consult);
    // 关闭loading状态
    loading.value = false;
    console.log('orderId', res);
    // 设置订单数据
    orderId.value = res.id;
    // 显示支付选项
    show.value = true;
    // 清空 consultStore
    // 开发的时候先注释掉
    // consultStore.clear();
  } catch (error) {
    loading.value = false;
  }
};

// 支付方式关闭前回调
const onBeforeClose = () => {
  console.log('before close');
  return Dialog.confirm({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付',
    confirmButtonColor: 'var(--cp-primary)',
  })
    .then((succ) => {
      console.log('继续支付');
      return false;
    })
    .catch((cancel) => {
      console.log('仍要关闭');
      // 如果用户仍然关闭，清空订单id
      orderId.value = '';
      // 跳转到问诊订单
      router.push('/user/consult');
      return true;
    });
};

// 监听路由的离开
onBeforeRouteLeave(() => {
  // 生成订单后才阻止回跳
  if (orderId.value) {
    return false;
  }
});

// 获取支付地址
const pay = async () => {
  if (paymentMethod.value === undefined) return Toast('请选择支付方式');
  const res = await getConsultOrderPayUrl({
    paymentMethod: paymentMethod.value,
    orderId: orderId.value,
    payCallback: 'http://127.0.0.1:5173/room',
  });
  console.log(res.payUrl);
  window.location.href = res.payUrl;
};
</script>

<template>
  <div class="consult-pay">
    <CpNavBar title="支付" />
    <!-- 支付信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <!-- 优惠券信息 -->
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo?.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo?.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`-¥${payInfo?.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>

    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="
          patient?.name +
          ' | ' +
          patient?.genderValue +
          ' | ' +
          patient?.age +
          '岁'
        "
      ></van-cell>
      <van-cell
        title="病情描述"
        :label="consultStore.consult.illnessDesc"
      ></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>

    <!-- 底部支付栏 -->
    <van-submit-bar
      button-type="primary"
      :loading="loading"
      :price="payInfo?.actualPayment && payInfo.actualPayment * 100"
      button-text="立即支付"
      @click="submit"
      text-align="left"
    />

    <!-- 支付选项UI -->
    <!-- 支付方式选项 -->
    <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :closeable="false"
      :before-close="onBeforeClose"
      :close-on-popstate="false"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo?.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><CpIcon name="consult-wechat" /></template>
            <template #extra
              ><van-checkbox :modelValue="paymentMethod === 0"
            /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><CpIcon name="consult-alipay" /></template>
            <template #extra
              ><van-checkbox :modelValue="paymentMethod === 1"
            /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay"
            >立即支付</van-button
          >
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<style lang="scss" scoped>
.consult-pay {
  padding-bottom: 50px;
  // 支付信息
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
  // 优惠券信息
  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }
      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }
  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }
  // 患者信息
  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    .text {
      color: var(--cp-primary);
    }
  }
  // 底部支付栏
  ::v-deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
    }
  }
  // 支付方式
  .pay-type {
    .amount {
      padding: 20px;
      text-align: center;
      font-size: 16px;
      font-weight: bold;
    }
    .btn {
      padding: 15px;
    }
    .van-cell {
      align-items: center;
      .cp-icon {
        margin-right: 10px;
        font-size: 18px;
      }
      .van-checkbox :deep(.van-checkbox__icon) {
        font-size: 16px;
      }
    }
  }
}
</style>
